<?php
namespace app\api\controller;

use app\common\model\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use think\Db;
use think\Queue;
use app\api\model\Clue as ApiClueModel;

class Acceptclue
{
    //加解密私钥
    const PRIVATE_KEY = "bBNuwPL42jnQXXZu";

    //投放账号: 车抵融
    const ACCOUNT_ID = 9520;

    //车抵融
    public function carPush()
    {
        $post = \input('post.');

        if (empty($post) || empty($post['data'])) {
            return Json(['msg' => '请求参数有误', 'status' => 200, "code" => 500]);
        }
        //解密
        $postData = openssl_decrypt($post['data'],'aes-128-ecb',self::PRIVATE_KEY, 0);
        writelog("车抵融请求 接收原参数:" . json_encode($post, JSON_UNESCAPED_UNICODE). ",解密后参数:". $postData);

        $postData = json_decode($postData, true);

        $aid = self::ACCOUNT_ID;
        $insertLog = [
            'api_url' => '车抵融',
            'adv_id' => $aid,
            'phone' => isset($postData['userPhone']) ? $postData['userPhone'] : '',
            'name' => isset($postData['userName']) ? $postData['userName'] : '',
            'city' => isset($postData['area']) ? $postData['area'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($postData, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $apiId = Db::name('clue_api_log')->insertGetId($insertLog);

        if (empty($postData['userName'])) {
            ApiClueModel::setClueApiLogError($apiId, '姓名不能为空');
            return Json(['msg' => '姓名不能为空', 'status' => 200, "code" => 500]);
        }

        if (empty($postData['userPhone'])) {
            ApiClueModel::setClueApiLogError($apiId, '手机号不能为空');
            return Json(['msg' => '手机号不能为空', 'status' => 200, "code" => 500]);
        }

        if (empty($postData['area'])) {
            ApiClueModel::setClueApiLogError($apiId, '城市不能为空');
            return Json(['msg' => '城市不能为空', 'status' => 200, "code" => 500]);
        }

        //加单机锁10s todo
        /*$redis = redis();
        $lock_key = config('config.prefix') . "accept_clue_phone_" . $postData['userPhone'];
        if ($redis->get($lock_key)) {
            return Json(['msg' => '线索手机重复请求', 'status' => 200, "code" => 202]);
        }
        $redis->setex($lock_key, 10, 1);*/

        //单机锁 end todo

        // 车抵
        $pro_id = 4;

        //优先级：房>车>公积金
        //产品为公积金
        if (!empty($postData['socialSecurityNum'])) {
            $pro_id = 6;
        }

        //产品为车
        if (!empty($postData['vehicleNum'])) {
            $pro_id = 4;
        }

        //产品为房
        if (!empty($postData['houseNum'])) {
            $pro_id = 3;
        }

        $params['clue_id'] = create_no('CDR');
        $params['adv_id'] = $aid;;
        $params['clue_name'] = $postData['userName'];
        $params['phone'] = $postData['userPhone'];
        $params['city'] = $postData['area'];
        $params['apply_limit'] = isset($postData['applyPrice']) ? $postData['applyPrice'] : 0;
        $params['age'] = 0;
        $params['gender'] = 0;
        $params['pro_id'] = $pro_id;
        $params['ip'] = isset($postData['ip']) ? $postData['ip'] : get_client_ip();

        $car = $house = $public_funds = $remark = [];
        if (!empty($postData['qualifications'])) {

            //按逗号区分 公积金， 房，车 等等
            $qualifications_array = explode(',', $postData['qualifications']); //资产列表：房，车
            foreach ($qualifications_array as $value) {
                $qualifications_detail_array = explode('-', $value); //具体资产数组:车

                $type = $qualifications_detail_array[0] ?? ""; //资产类型名称
                if ($type == '车') {
                    unset($qualifications_detail_array[0]);
                    $car = $qualifications_detail_array;
                    $remark[] = ['车' => implode("-", $car)];
                } elseif ($type == '房') {
                    unset($qualifications_detail_array[0]);
                    $house = $qualifications_detail_array;
                    $remark[] = ['房' => implode("-", $house)];
                } elseif ($type == '公积金') {
                    unset($qualifications_detail_array[0]);
                    $public_funds = $qualifications_detail_array;
                    $remark[] = ['公积金' => implode("-", $public_funds)];
                }
            }
        }

        $params['car'] = !empty($car) ? implode("|", $car) : "";
        $params['house'] = !empty($house) ? implode("|", $house) : "";
        $params['public_funds'] = !empty($public_funds) ? implode("|", $public_funds) : "";
        $params['remark'] = !empty($remark) ? json_encode($remark, JSON_UNESCAPED_UNICODE) : "";

        $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
        if ($isDayPhone) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索已存在', $params);
            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
            return Json(['msg' => '线索已存在', 'status' => 200, "code" => 202]);
        }

        $isAid = Db::name('account')->where('adv_id', $aid)->find();
        if ($isAid['status'] != 1) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
            ApiClueModel::setClueApiLogError($apiId, '账户已禁用');
            return Json(['msg' => '账户已禁用', 'status' => 200, "code" => 500]);
        }
        $params['type'] = $isAid['channel_id'];

        $isBlack = model('clue')->where(['phone' => $params['phone'], 'is_black' => 1])->find();
        if ($isBlack) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '黑名单线索', $params);
            ApiClueModel::setClueApiLogError($apiId, '黑名单线索');
            return Json(['msg' => '进线失败，黑名单线索', 'status' => 200, "code" => 500]);
        }

        if (strpos($params['city'], '|') !== false) {
            $city_t = explode('|', $params['city']);
        } elseif (strpos($params['city'], '-') !== false) {
            $city_t = explode('-', $params['city']);
        } else {
            $city_t = [$params['city']];
        }

        $city_info = clue_city_transform($city_t);

        if (!$city_info) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
//            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
            $params['city'] = '';
            $params['err_msg'] = '未匹配到城市id城市解析失败';
        } else {
            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
            $params['city'] = $province['id'] . '-' . $city_info['id'];
        }

        //城市是否禁用
        $isCity = model('accountCity')->where(['acc_id' => $isAid['id'], 'city' => $params['city'], 'status' => 1])->find();
        if (!empty($isCity)) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
            //return Json(['msg' => '账户城市已禁用', 'status' => 200, "code" => 500]);
            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
            return Json(['msg' => '线索已存在', 'status' => 200, "code" => 202]);
        }

        // 城市是否准入
        $is_allow = (new \app\common\model\Clue())->allowAccountCity($isAid['id'], $params['city']);
        if ($is_allow === false) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市不准入', $post);
            ApiClueModel::setClueApiLogError($apiId, '账户城市不准入');
            return Json(['msg' => '线索已存在', 'status' => 200, "code" => 202]);
        }

        $clueCost = model('ClueAddCost')
            ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
            ->where('status', 1)
            ->find();
        if (empty($clueCost)) {
            // 找不到城市就找默认全国城市
            $clueCost = model('ClueAddCost')
                ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
                ->where('status', 1)
                ->find();
        }
        if (!empty($clueCost)) {
            $params['price'] = $clueCost['money'];
            $params['true_price'] = $clueCost['money'];
            $params['xz_price'] = $clueCost['money'];
            $params['xz_true_price'] = $clueCost['money'];
            $params['xz_price2'] = $clueCost['money'];
            $params['xz_true_price2'] = $clueCost['money'];
        } else {
            $params['price'] = $isAid['clue_cost'];
            $params['true_price'] = $isAid['clue_cost'];
            $params['xz_price'] = $isAid['clue_cost'];
            $params['xz_true_price'] = $isAid['clue_cost'];
            $params['xz_price2'] = $isAid['clue_cost'];
            $params['xz_true_price2'] = $isAid['clue_cost'];
        }
        $params['account_id'] = $isAid['id'];
        //判断线索重复
        $isClue = model('clue')->where(['phone' => $params['phone']])->find();

        // 1.记录线索
        $clueModel = new \app\common\model\Clue();
        $res = $clueModel->saveData($params);
        $id = $clueModel->id;

        if ($res['code'] != 1000) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
            return Json(['msg' => '线索接收失败', 'status' => 200, "code" => 500]);
        }

        Db::name('clue_api_log')->where('id', $apiId)->update(['status' => 1]);

        if ($isClue) {
            Db::name('clue_err_log')->insert(['type' => 1, 'phone' => $params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
        }

        if (empty($params['city'])) {
            return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
        }

        if (strpos($params['clue_name'], '测试') !== false) {
            return Json(['status' => 200, 'msg' => '测试线索接收成功', 'code' => 200]);
        }

        // 2.推送线索
//        $clue_info = $clueModel->find($id);
//
//        $res = $this->cluePush($clue_info, true);

        $jobHandlerClassName = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName = "ExprotClue";

        $jobData = ['id' => $id];

        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
    }
}